<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 新闻列表
 * @author chaituan@126.com
 */
class News extends AdminCommon {
	public function __construct() {
		parent::__construct ();
		$this->load->model(array('admin/News_model'=>'do','admin/NewsCat_model'=>'do_cat'));
	}
	
	public function index() {
		$this->load->view ('admin/news/index');
	}
	
	//页面table获取数据
	function lists(){
		$name = Gets('name');//搜索
		$page = Gets('page','checkid');$limit = Gets('limit','checkid');
		$total = Gets('total','num');
		$where = $name?"news.title like '%$name%'":'';
		$data = $this->do->getItems_join (array('newscat' => "news.catid=newscat.id+left"),$where,'news.*,newscat.catname','addtime desc',$page,$limit,$total);
		$find = Gets('find');//mark 为了 第一次查询请求判断，
		if(($name&&$find)||!$total){//当name和find有值的时候，代表是第一次查询，分页点击只有find为空值
			$total = $this->do->count;
		}
		f_ajax_lists($total, $data);
	}
	
	
	public function add() {
		if (is_ajax_request ()) {
			$data = Posts('data');
			$data['state'] = isset($data['state'])?1:0;
			$data['addtime'] = time ();
			$con = Posts('data[content]','',false);
			$data['content'] = htmlspecialchars_decode($con, ENT_QUOTES);//单独为content 编译
			is_AjaxResult($this->do->add($data));
		} else {
			$data ['cat'] = $this->do_cat->get_cat();
			$this->load->view ( 'admin/news/add', $data );
		}
	}
	
	public function edit() {
		if (is_ajax_request ()) {
			$data = Posts ( 'data' );
			$data['state'] = isset($data['state'])?1:0;
			$con = Posts('data[content]','',false);
			$data['content'] = htmlspecialchars_decode($con, ENT_QUOTES);//单独为content 编译
			is_AjaxResult ( $this->do->updates ( $data, "id=" . Posts ( 'id', 'checkid' ) ) );
		} else {
			$id = Gets ( "id", "checkid" );
			$data ['cat'] = $this->do_cat->get_cat ();
			$data ['item'] = $this->do->getItem ( "id=$id" );
			$this->load->view ( 'admin/news/edit', $data );
		}
	}
	
	function del() {
		$id = Gets ('id','checkid');
		$result = $this->do->deletes(array('id'=>$id));
		is_AjaxResult($result);
	}
	
	public function dels() {
		$data = Posts();
		if (!$data)AjaxResult_error('没有选中要删除的');
		$ids = implode(',', $data['checked']);
		$result = $this->do->deletes("id in ($ids)");
		if ($result) {
			AjaxResult(1,"删除成功",$data['checked']);
		} else {
			AjaxResult(2,"删除失败");
		}
	}
	
	function lock(){
		sleep(1);
		$id = Gets ('id','checkid');
		$open = Gets('open','checkid');
		$result = $this->do->updates(array('state'=>$open),array('id'=>$id));
		is_AjaxResult($result);
	}
	
	private function get_cat() {
		$cat = $this->do_cat->get_cat ();
		if ($cat) {
			foreach ( $cat as $v ) {
				$new [$v ['id']] = $v;
			}
		} else {
			redirect ( site_url ( 'adminct/newscat/index' ) );
		}
		return $new;
	}
}
